﻿using Caliburn.Micro;
using System;
using System.Windows;
using System.Windows.Controls;

namespace GetMan.Results
{
    public class FocusResult : ResultBase
    {
        private readonly string _controlName;

        public FocusResult(string controlName)
        {
            _controlName = controlName;
        }

        public override void Execute(CoroutineExecutionContext context)
        {
            if (!(context.View is FrameworkElement))
                throw new InvalidOperationException("View must be a FrameworkElement to use VisualStateResult");
            var view = (FrameworkElement)context.View;
            var control = view.FindName(_controlName);
            if (control is Control c)
            {
                c.Focus();
                if (c is TextBox textBox)
                {
                    textBox.CaretIndex = textBox.Text.Length;
                }
            }
        }
    }
}